import React, { Component, createRef } from "react";

import styles from "./index.module.css";

import PropTypes from "prop-types";

class Sticky extends Component {
  // 创建 ref 对象
  placeholder = createRef();
  content = createRef();
  // scroll 事件的处理程序
  handleScroll = () => {
    const { height } = this.props;
    //   获取 DOM 对象
    const placeholderE1 = this.placeholder.current;
    const contentE1 = this.content.current;
    const { top } = placeholderE1.getBoundingClientRect();
    if (top < 0) {
      //   吸顶
      contentE1.classList.add(styles.fixed);
      // 占位元素
      placeholderE1.style.height = `${height}px`;
    } else {
      // 取消吸顶
      contentE1.classList.remove(styles.fixed);
      placeholderE1.style.height = "0";
    }
  };
  // 监听 scroll 事件
  componentDidMount() {
    window.addEventListener("scroll", this.handleScroll);
  }
  // 销毁 scroll 事件
  componentWillUnmount() {
    window.removeEventListener("scroll", this.handleScroll);
  }
  render() {
    return (
      <div>
        {/* 占位元素 */}
        <div ref={this.placeholder}></div>
        {/* 内容元素 */}
        <div ref={this.content}> {this.props.children}</div>
      </div>
    );
  }
}

Sticky.propTypes = {
  height: PropTypes.number.isRequired,
};

export default Sticky;
